from django.shortcuts import render
import os
import random
import qrcode
import tempfile
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from django.conf import settings
from .models import PayOrder
from .serializers import PayOrderSerializer
from django.contrib.auth import get_user_model
from dotenv import load_dotenv
from base64 import b64encode

# 加载环境变量
env_path = os.path.join(settings.BASE_DIR, 'dockers', 'env.conf')
if os.path.exists(env_path):
    load_dotenv(env_path, override=True)

User = get_user_model()

# 支付宝依赖
from alipay import AliPay

# 微信支付依赖
import hashlib
import requests
from datetime import datetime
import pytz
from utils.settings.log_config import logger
from dotenv import load_dotenv

load_dotenv('.env', verbose=True)
# 工具函数：图片转base64
def save_img_to_base64(img_path):
    with open(img_path, 'rb') as f:
        return b64encode(f.read()).decode()

class AliPayOrderView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        amount = request.data.get('amount')
        description = request.data.get('description', '商品购买')
        order_no = f"ALI{random.randint(100000, 999999)}{user.id}{int(datetime.now().timestamp())}"
        # 读取配置
        app_id = os.getenv('ALI_PAY_ID')
        app_private_key_string = os.getenv('ALI_PRIVATE_KEY')
        alipay_public_key_string = os.getenv('ALI_PUBLIC_KEY')
        logger.info(f"app_id: {app_id}, app_private_key_string: {app_private_key_string}, alipay_public_key_string: {alipay_public_key_string}")
        notify_url = os.getenv('ALI_NOTIFY_URL')
        logger.info(f"notify_url: {notify_url}")
        logger.info(f"app_id: {app_id}, app_private_key_string: {app_private_key_string}, alipay_public_key_string: {alipay_public_key_string}")
        logger.info(f"app_id: {app_id}, app_private_key_string: {app_private_key_string}, alipay_public_key_string: {alipay_public_key_string}")
        if not AliPay:
            return Response({'error': 'alipay sdk not installed'}, status=500)
        alipay = AliPay(
            appid=app_id,
            app_notify_url=notify_url,
            app_private_key_string=f"""-----BEGIN RSA PRIVATE KEY-----\n{app_private_key_string}\n-----END RSA PRIVATE KEY-----""",
            alipay_public_key_string=f"""-----BEGIN PUBLIC KEY-----\n{alipay_public_key_string}\n-----END PUBLIC KEY-----""",
            sign_type="RSA2",
            debug=False
        )
        order_response = alipay.api_alipay_trade_precreate(
            out_trade_no=order_no,
            total_amount=str(amount),
            subject=description,
            return_url=None,
            notify_url=notify_url
        )
        qr_code_url = order_response.get('qr_code')
        if not qr_code_url:
            return Response({'error': '未获取到二维码链接', 'alipay_response': order_response}, status=500)
        # 记录订单
        order = PayOrder.objects.create(
            order_no=order_no,
            user=user,
            amount=amount,
            description=description,
            pay_type='alipay',
            status='pending',
        )
        serializer = PayOrderSerializer(order)
        return Response({'order': serializer.data, 'qrcode_url': qr_code_url})

class WeChatPayOrderView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        amount = request.data.get('amount')
        description = request.data.get('description', '商品购买')
        order_no = f"WX{random.randint(100000, 999999)}{user.id}{int(datetime.now().timestamp())}"
        # 读取配置
        app_id = os.getenv('WX_PAY_ID')
        mch_id = os.getenv('WX_MCH_ID')
        api_key = os.getenv('WX_APIU_KEY')
        notify_url = os.getenv('WX_NOTIFY_URL')
        create_ip = request.META.get('REMOTE_ADDR', '127.0.0.1')
        trade_type = 'NATIVE'
        nonce_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=16))
        total_fee = int(float(amount) * 100)
        params = {
            'appid': app_id,
            'mch_id': mch_id,
            'nonce_str': nonce_str,
            'out_trade_no': order_no,
            'total_fee': total_fee,
            'spbill_create_ip': create_ip,
            'notify_url': notify_url,
            'body': description,
            'trade_type': trade_type,
        }
        # 签名
        params_list = sorted(params.items(), key=lambda e: e[0])
        params_str = "&".join(f"{k}={v}" for k, v in params_list) + f"&key={api_key}"
        sign = hashlib.md5(params_str.encode('utf-8')).hexdigest().upper()
        params['sign'] = sign
        # 转xml
        def dict_to_xml(data):
            xml = ["<xml>"]
            for k, v in data.items():
                xml.append(f"<{k}>{v}</{k}>")
            xml.append("</xml>")
            return ''.join(xml)
        xml = dict_to_xml(params)
        # 请求微信
        resp = requests.post('https://api.mch.weixin.qq.com/pay/unifiedorder', data=xml.encode('utf-8'))
        import xml.etree.ElementTree as ET
        root = ET.fromstring(resp.content)
        result = {child.tag: child.text for child in root}
        code_url = result.get('code_url')
        # 生成二维码
        # if code_url:
        #     with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
        #         img = qrcode.make(code_url)
        #         img.save(tmp.name)
        #         base_qrcode = save_img_to_base64(tmp.name)
        #     os.remove(tmp.name)
        # else:
        #     base_qrcode = None
        # 记录订单
        order = PayOrder.objects.create(
            order_no=order_no,
            user=user,
            amount=amount,
            description=description,
            pay_type='wechat',
            status='pending',
        )
        serializer = PayOrderSerializer(order)
        return Response({'order': serializer.data, 'qrcode': code_url, 'wx_result': result})
